<template>
  <div class="afterManage-combination-page app-container">
    <div class="container">
      <div class="container-header">
        <div class="left">
          <div class="title">投资组合</div>
          <el-form
            ref="dateForm"
            :inline="true"
            label-width="80px"
            :model="dateForm"
          >
            <el-form-item label="" prop="compositionName">
              <el-input
                v-model="dateForm.compositionName"
                clearable
                size="small"
                placeholder="请输入组合名称"
                style="width: 260px"
                @keyup.enter.native="getList"
              ></el-input>
            </el-form-item>
            <el-form-item label="" prop="mark">
              <el-input
                v-model="dateForm.mark"
                clearable
                size="small"
                placeholder="请输入备注"
                style="width: 260px"
                @keyup.enter.native="getList"
              ></el-input>
            </el-form-item>
            <el-form-item style="margin-left: 20px">
              <el-button class="bg-green" @click="getList" size="small">
                查询
              </el-button>
              <el-button size="small" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="right-btn">
          <el-button
            v-if="!isOpen"
            type="primary"
            size="small"
            @click="addOrUpdateHandle()"
          >
            <i class="el-icon-plus el-icon--right"></i>
            添加
          </el-button>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        stripe
        fit
        size="mini"
        lazy
        :row-key="(row) => row.compositionId"
        @sort-change="sortChange"
        @row-click="submitHandle"
        :header-cell-style="{ color: '#333' }"
        style="width: 100%"
      >
        <!-- :tree-props="{ children: 'children', hasChildren: 'hasClassify' }" -->
        <!-- :load="loadChildTable" -->
        <el-table-column
          type=""
          prop="compositionId"
          label="编号"
          align="left"
          width="80"
          fixed
          sortable="custom"
        ></el-table-column>
        <el-table-column
          prop="compositionName"
          label="组合名称"
          min-width="290"
          fixed
          sortable="custom"
        >
          <template slot-scope="{ row, $index }">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: flex-start;
              "
            >
              <div
                v-if="row.hasNetWorth && !row.classifyId"
                @click="loadChildTable(row, $index)"
              >
                <svg
                  v-show="row.treeHas"
                  class="icon svg-icon"
                  aria-hidden="true"
                >
                  <use xlink:href="#icon-a-Icon-shouqi"></use>
                </svg>
                <svg
                  v-show="!row.treeHas"
                  class="icon svg-icon"
                  aria-hidden="true"
                >
                  <use xlink:href="#icon-Icon-zhankai"></use>
                </svg>
              </div>
              <div
                style="
                  overflow: hidden;
                  text-overflow: ellipsis;
                  display: -webkit-box;
                  -webkit-line-clamp: 2;
                  -webkit-box-orient: vertical;
                "
                :title="row.compositionName"
              >
                <div
                  v-if="row.hasNetWorth && !row.classifyId"
                  style="cursor: pointer; color: #1890ff"
                  @click.stop="groupDeltailHandle(row.compositionId)"
                >
                  {{ row.compositionName }}
                </div>
                <div
                  v-else-if="row.classifyId"
                  style="cursor: pointer; color: #1890ff; margin-left: 40px"
                  @click.stop="classifyDeltailHandle(row.classifyId)"
                >
                  {{ row.classfyName }}
                </div>
                <div
                  v-else
                  style="cursor: pointer; color: #666"
                  @click.stop="$message('该投资分组净值不存在，无法查看详情')"
                >
                  {{ row.compositionName }}
                </div>
              </div>
              <el-popover
                v-if="row.mark"
                popper-class="policyManage_popover"
                trigger="hover"
                placement="right"
                style="cursor: pointer"
              >
                <div class="flex-vh-center">
                  {{ row.mark }}
                </div>
                <div slot="reference">
                  <i
                    class="el-icon-document fontdoc"
                    style="font-size: 16px"
                  ></i>
                </div>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="" label="对比" align="center" fixed>
          <template slot-scope="{ row, $index }">
            <span
              v-if="row.hasNetWorth"
              class="pointer"
              :class="{ fontcolor: !row.addContrast }"
              @click="addContrasthandle(row, $index)"
            >
              <span v-show="!row.addContrast" class="iconfont icon-jia" />
              <span
                v-show="row.addContrast"
                class="iconfont icon-check contrastGray"
              />
              <span
                :class="{ contrastGray: row.addContrast }"
                style="padding-left: 2px"
              >
                {{ !row.addContrast ? "对比" : "已加" }}
              </span>
            </span>
            <span
              v-else
              class="contrastGray"
              @click.stop="$message('该组合净值不存在，不能对比')"
            >
              <span class="iconfont icon-jia" />
              <span style="padding-left: 2px">对比</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="netWorthTime"
          label="净值日期"
          width="100"
          align="center"
          sortable="custom"
        >
          <template slot-scope="{ row }">
            <span>{{ row.netWorthTime | parseTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="netWorthValue"
          label="单位净值"
          width="130"
          align="center"
          sortable="custom"
        ></el-table-column>
        <el-table-column
          prop="netWorthValue"
          label="累计净值"
          width="130"
          align="center"
          sortable="custom"
        ></el-table-column>
        <el-table-column
          prop="virNetworth"
          label="虚拟净值"
          width="130"
          align="center"
          sortable="custom"
        ></el-table-column>
        <el-table-column
          prop="initMoney"
          label="资产金额(万元)"
          width="140"
          align="center"
          sortable="custom"
        ></el-table-column>
        <el-table-column
          prop="investManageShare"
          label="资产份额(份)"
          width="140"
          align="center"
          sortable="custom"
        ></el-table-column>
        <el-table-column
          prop="incomeRate"
          label="收益率"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable="custom"
        >
          <template slot-scope="{ row }">
            <span
              v-if="row.incomeRate || row.incomeRate !== null"
              :class="row.incomeRate >= 0 ? 'positiveFc' : 'negativeFc'"
            >
              {{ row.incomeRate }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="incomeRateToday"
          label="当日收益率"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable="custom"
        >
          <template slot-scope="{ row }">
            <span
              v-if="row.incomeRateToday || row.incomeRateToday !== null"
              :class="row.incomeRateToday >= 0 ? 'positiveFc' : 'negativeFc'"
            >
              {{ row.incomeRateToday }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="incomeRateThisWeek"
          label="近1周收益率"
          min-width="130"
          show-overflow-tooltip
          align="center"
          sortable="custom"
        >
          <template slot-scope="{ row }">
            <span
              v-if="row.incomeRateThisWeek"
              :class="row.incomeRateThisWeek >= 0 ? 'positiveFc' : 'negativeFc'"
            >
              {{ row.incomeRateThisWeek }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="incomeRateMonth"
          label="近1月收益率"
          min-width="130"
          show-overflow-tooltip
          align="center"
          sortable="custom"
        >
          <template slot-scope="{ row }">
            <span
              v-if="row.incomeRateMonth"
              :class="row.incomeRateMonth >= 0 ? 'positiveFc' : 'negativeFc'"
            >
              {{ row.incomeRateMonth }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="incomeRateHalfYear"
          label="近6月收益率"
          min-width="130"
          show-overflow-tooltip
          align="center"
          sortable="custom"
        >
          <template slot-scope="{ row }">
            <span
              v-if="row.incomeRateHalfYear"
              :class="row.incomeRateHalfYear >= 0 ? 'positiveFc' : 'negativeFc'"
            >
              {{ row.incomeRateHalfYear }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="incomeRateYear"
          label="近1年收益率"
          min-width="130"
          show-overflow-tooltip
          align="center"
          sortable="custom"
        >
          <template slot-scope="{ row }">
            <span
              v-if="row.incomeRateYear"
              :class="row.incomeRateYear >= 0 ? 'positiveFc' : 'negativeFc'"
            >
              {{ row.incomeRateYear }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdTime"
          label="创建日期"
          min-width="100"
          show-overflow-tooltip
          align="center"
          sortable="custom"
        ></el-table-column>
        <el-table-column
          v-if="!isOpen"
          label="操作"
          align="center"
          width="230"
          fixed="right"
        >
          <template slot-scope="{ row }">
            <div v-if="!row.classifyId">
              <el-button
                class="filter-item"
                size="mini"
                @click="addOrUpdateHandle(row)"
              >
                配置组合
              </el-button>
              <el-button
                class="filter-item"
                size="mini"
                icon="el-icon-connection"
                @click="goAfterInvestHandle(row)"
              >
                下属投资
              </el-button>
              <!-- <el-popover
                popper-class="policyManage_popover"
                trigger="hover"
                placement="bottom"
              >
                <div class="flex-vh-center">
                  <el-button
                    class="filter-item"
                    size="mini"
                    @click="
                      subscribeHandle(row.compositionId, row.compositionName, 1)
                    "
                  >
                    申购/入金
                  </el-button>
                  <el-button
                    style="margin: 10px 0;"
                    class="filter-item"
                    size="mini"
                    @click="
                      subscribeHandle(row.compositionId, row.compositionName, 2)
                    "
                  >
                    赎回/出金
                  </el-button>
                  <el-button
                    style="margin: 0;"
                    class="filter-item"
                    size="mini"
                    @click="openSetWarehouse(row)"
                  >
                    调仓记录
                  </el-button>
                </div>
                <span class="operationMore" slot="reference">
                  <el-button class="filter-item" size="mini">
                    调仓
                  </el-button>
                </span>
              </el-popover> -->
              <el-popover
                popper-class="policyManage_popover"
                trigger="hover"
                placement="bottom"
              >
                <div class="flex-vh-center">
                  <el-button
                    class="filter-item"
                    size="mini"
                    style="margin: 10px 0 0 0"
                    icon="el-icon-delete"
                    @click="deleteHandle(row)"
                  >
                    删除
                  </el-button>
                </div>
                <span class="operationMore" slot="reference">...</span>
              </el-popover>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.pageCurrent"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
      <addOrUpdateDialog
        ref="addOrUpdateOpen"
        @closeOpen="getList"
        :type="dialogType"
        :addOrUpdateView.sync="addOrUpdateView"
        :row="listRow"
      ></addOrUpdateDialog>
      <globalContrastOpen
        ref="globalContrastOpen"
        :list="contrastList"
      ></globalContrastOpen>
      <subscribeOpen
        v-if="subscribeView"
        ref="subscribeOpen"
        :userId="userId"
        @closeOpen="getList"
      ></subscribeOpen>
      <setWarehouse
        :row="listRow"
        :type="0"
        :warehouseDialogVisible.sync="warehouseDialogVisible"
      ></setWarehouse>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Pagination from "@/components/Pagination";
import {
  deleteInvestCompositionNetWorth,
  findAllManageCompositions,
  findAllManageClassifys,
} from "@/api/combination";
import addOrUpdateDialog from "./dialog";
import subscribeOpen from "@/views/afterManage/component/subscribeOpen.vue";
import globalContrastOpen from "@/components/investComn/globalContrastOpen.vue";
import { rmoney } from "@/utils";
import setWarehouse from "@/views/afterManage/component/setWarehouse.vue";

export default {
  name: "AfterManageCombination",
  components: {
    addOrUpdateDialog,
    Pagination,
    subscribeOpen,
    setWarehouse,
    globalContrastOpen,
  },
  props: {
    isOpen: {
      type: Boolean,
      defaultL: false,
    },
  },
  data() {
    return {
      addOrUpdateView: false,
      subscribeView: false,
      listLoading: false,
      warehouseDialogVisible: false,
      dateForm: { mark: "" },
      total: 0,
      list: [{ strategyInfoVo: {}, investManageVo: {} }],
      listRow: {},
      dialogType: "add",
      listQuery: {
        pageCurrent: 1,
        limit: 20,
      },
      rmoney: Function,
      orderByInfo: {},
    };
  },
  computed: {
    ...mapGetters(["userId", "contrastList"]),
  },
  watch: {
    contrastList(newList, oldList) {
      if (newList.length == oldList.length) {
        // todo 此处newList==oldList则是数组减少，未知原因
        this.syncContrastListHandle();
      }
      if (!newList.length) {
        this.list.forEach((row, i) => {
          row.addContrast = false;
          // this.$set(this.list, i, row)
        });
      }
    },
  },
  created() {
    this.rmoney = rmoney;
    this.getList();
  },
  methods: {
    openSetWarehouse(row) {
      this.listRow = row;
      this.warehouseDialogVisible = true;
    },
    subscribeHandle(compositionId, compositionName, isSubscribe) {
      this.subscribeView = true;
      this.$nextTick(() => {
        this.$refs.subscribeOpen.init(
          compositionId,
          compositionName,
          isSubscribe,
          0
        );
      });
    },
    sortChange(column) {
      if (!column.order) {
        this.orderByInfo = {};
      } else {
        this.orderByInfo = {
          [column.prop]: column.order == "ascending" ? "asc" : "desc",
        };
      }
      this.getList();
    },
    // 同步对比框数据和列表数据
    syncContrastListHandle() {
      if (!this.contrastList.length) {
        this.list.forEach((row, i) => {
          row.addContrast = false;
          // this.$set(this.list, i, row)
        });
      } else {
        const list = this.contrastList.filter(
          (item) => item.contrastObj.type == 6
        );
        this.list.forEach((row, index) => {
          row.addContrast = false;
          this.$set(this.list, index, row);
          const i = list.findIndex(
            (item) => item.contrastObj.id == row.compositionId
          );
          if (i != -1) {
            this.list[index].addContrast = true;
          }
        });
      }
    },
    addContrasthandle(row, i) {
      this.$refs.globalContrastOpen.showOpen = true;
      this.$store.commit("contrast/toggleShowOpen", true);
      row.addContrast = !row.addContrast;
      if (this.contrastList.length == 20) {
        this.$message({
          message: "最多添加20条数据",
          type: "warning",
        });
        return;
      }
      // this.$set(this.list, i, row) // 更新表格数据s
      if (row.addContrast) {
        row.contrastObj = {
          type: 6,
          id: row.compositionId,
          name: row.compositionName,
          annualFluctuations: row.netWorthDetialBean.yearAnnualfluctuationsRate,
          annualizedIncome: row.netWorthDetialBean.yearAnnualizedincomeRate
        };
        this.$store.commit("contrast/addContrastList", row);
      } else {
        const i = this.contrastList.findIndex(
          (item) =>
            item.contrastObj.id == row.compositionId &&
            item.contrastObj.type == 6
        );
        this.$store.commit("contrast/removeContrastList", i);
      }
    },
    groupDeltailHandle(id) {
      this.$router.push({
        path: `/afterManage/combination/details/${id}`,
      });
    },
    classifyDeltailHandle(id) {
      this.$router.push({
        path: `/afterManage/investType/details/${id}`,
      });
    },
    goAfterInvestHandle(row) {
      this.$router.push({
        path: "/afterManage/investList",
        query: {
          compositionId: row.compositionId,
        },
      });
    },
    submitHandle(row) {
      this.$emit("selctCombination", {
        compositionId: row.compositionId,
        compositionName: row.compositionName,
      });
    },
    addOrUpdateHandle(row) {
      this.listRow = {};
      if (row) {
        this.listRow = row;
        this.dialogType = "update";
      } else {
        this.dialogType = "add";
      }
      this.addOrUpdateView = true;
    },
    loadChildTable(row, index, resolve) {
      if (row.treeHas) {
        this.list = this.list.filter((item) => {
          if (item.compositionName === row.compositionName && item.classifyId) {
            return false;
          }
          return item;
        });
        row.treeHas = false;
        return;
      }
      findAllManageClassifys({
        compositionId: row.compositionId,
        userId: this.userId,
        pageCurrent: 1,
        limit: 1000,
      }).then((res) => {
        row.treeHas = true;
        res.body.list.map((item) => {
          item.old_compositionId = item.compositionId;
          item.compositionId = "Z" + item.classifyId;
        });
        const i = index + 1;
        this.list.splice(i, 0, ...res.body.list);
      });
    },
    deleteHandle(row) {
      this.$confirm(
        `确认删除分组名称【${row.compositionName}】此条数据？`,
        "提示",
        {
          type: "warning",
        }
      )
        .then((_) => {
          deleteInvestCompositionNetWorth({
            compositionId: row.compositionId,
          }).then((res) => {
            if (res.code == 0) {
              this.$notify({
                message: res.msg,
                type: "success",
                duration: 2000,
              });
              this.getList();
            }
          });
        })
        .catch((_) => {});
    },
    resetForm() {
      this.$refs.dateForm.resetFields();
      this.getList();
    },
    getList() {
      this.listLoading = true;
      findAllManageCompositions({
        ...this.dateForm,
        ...this.listQuery,
        orderByInfo: this.orderByInfo,
        userId: this.userId,
      }).then((res) => {
        this.listLoading = false;
        this.list = res.body.list;
        this.total = res.body.total;
        if (this.contrastList.length) this.syncContrastListHandle();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.afterManage-combination-page {
  .svg-icon {
    width: 18px;
    height: 18px;
    margin-right: 5px;
    font-size: 18px;
    vertical-align: -0.18em;
    cursor: pointer;
  }
  .operationMore {
    padding-left: 10px;
    font-weight: bold;
    cursor: pointer;
  }
  .icon-jia {
    font-size: 12px;
  }
}
</style>
